package com.fenye.testflow.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fenye.testflow.mapper.SysRoleMapper;
import com.fenye.testflow.mapper.SysUserRoleMapper;
import com.fenye.testflow.mapper.TestRequestMapper;
import com.fenye.testflow.model.common.GuiguException;
import com.fenye.testflow.model.common.ResultCodeEnum;
import com.fenye.testflow.model.dto.TestRequestDto;
import com.fenye.testflow.model.entity.system.SysRole;
import com.fenye.testflow.model.entity.system.SysUser;
import com.fenye.testflow.model.entity.system.SysUserRole;
import com.fenye.testflow.model.entity.testflow.TestRequest;
import com.fenye.testflow.model.vo.TestRequestVo;
import com.fenye.testflow.service.TestRequestService;
import com.fenye.testflow.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class TestRequestServiceImpl extends ServiceImpl<TestRequestMapper, TestRequest> implements TestRequestService {

    @Autowired
    private TestRequestMapper testRequestMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public Boolean updateTestRequestStatusById(TestRequestDto testRequestDto) {
        if (testRequestDto.getRequestId() == null && testRequestDto.getRequestId() < 0 && testRequestDto.getStatus() == null) {
            new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        TestRequest testRequest = new  TestRequest();
        testRequest.setId(testRequestDto.getRequestId());
        //提测操作
        if (testRequestDto.getStatus().equals(2)){
            testRequest.setStatus(testRequestDto.getStatus());
            //获取当前时间并格式化
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedNow = formatter.format(new Date());
            Date date = null;
            try {
                date = formatter.parse(formattedNow);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            testRequest.setActualTestTime(date);
            testRequestMapper.updateById(testRequest);
            return true;

        }

        //驳回操作
        if (testRequestDto.getStatus().equals(3)){
            TestRequest DefaultTestRequest = testRequestMapper.selectById(testRequestDto.getRequestId());
            testRequest.setStatus(testRequestDto.getStatus());
            //提测失败，提测次数+1
            testRequest.setTestFailedNumber(DefaultTestRequest.getTestFailedNumber() +1 );
            testRequestMapper.updateById(testRequest);
            return true;

        }

        //提测成功
        if (testRequestDto.getStatus().equals(4)){
            SysUser sysUser = AuthContextUtil.get();
            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<SysUserRole>();
            queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
            SysUserRole sysUserRole = sysUserRoleMapper.selectOne(queryWrapper);
            SysRole sysRole = sysRoleMapper.selectById(sysUserRole.getRoleId());
            if (!"QA".equals(sysRole.getRoleCode()) && !"Admin".equals(sysRole.getRoleName())) {
                throw new GuiguException(ResultCodeEnum.NOQA);
            }
            testRequest.setStatus(testRequestDto.getStatus());
            testRequestMapper.updateById(testRequest);
            return true;
        }else {
            return false;
        }

    }


    /**
     *  @author: fenye
     *  @Date:
     *  @Description: 导出表格数据
     */
    @Override
    public Boolean exportData(TestRequest testRequest, HttpServletResponse response) {
        // 设置响应结果类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("提测单数据", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 查询数据库中的数据
        LambdaQueryWrapper<TestRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestRequest::getProjectId, testRequest.getProjectId());
        queryWrapper.eq(TestRequest::getVersionNumber, testRequest.getVersionNumber());
        List<TestRequest> testRequestList = testRequestMapper.selectList(queryWrapper);

        List<TestRequestVo> testRequestVoList = new ArrayList<>();
        //将数据库中查到的TestRequest对象，转换为TestRequestVo对象
        for (TestRequest testRequest1 : testRequestList) {
            TestRequestVo testRequestVo = new TestRequestVo();
            BeanUtils.copyProperties(testRequest1, testRequestVo,TestRequestVo.class);
            testRequestVoList.add(testRequestVo);
        }


        // 写数据到浏览器端
        try {
            EasyExcel.write(response.getOutputStream(),TestRequestVo.class).sheet("提测单数据").doWrite(testRequestVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }


    //查询用户待办
    @Override
    public Page<TestRequest> queryTodoTestRequest(Page pageParam) {
        SysUser sysUser = AuthContextUtil.get();
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<SysUserRole>();
        queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
        SysUserRole sysUserRole = sysUserRoleMapper.selectOne(queryWrapper);
        SysRole sysRole = sysRoleMapper.selectById(sysUserRole.getRoleId());

        LambdaQueryWrapper<TestRequest> testLambdaQueryWrapper = new LambdaQueryWrapper<>();
         Page<TestRequest> testRequestIPageParam  = new Page<>(pageParam.getPages(), pageParam.getSize());
        List<TestRequest> RequestList ;
        //查询用户为开发角色的待办清单
        if ("DEV".equals(sysRole.getRoleCode())){
            testLambdaQueryWrapper
                    .apply("JSON_CONTAINS(developers, {0}, '$')", String.valueOf(sysUser.getId()));
            List<Integer> status = new ArrayList<>();
            status.add(1);
            status.add(3);
            status.add(4);
            testLambdaQueryWrapper.notIn(TestRequest::getStatus,status);
            Page<TestRequest> pageData = this.page(testRequestIPageParam, testLambdaQueryWrapper);
            return pageData;



        }

        //查询角色为测试人员的待办清单
        if ("QA".equals(sysRole.getRoleCode())){
            testLambdaQueryWrapper
                    .apply("JSON_CONTAINS(testers, {0}, '$')", String.valueOf(sysUser.getId()));
            List<Integer> status = new ArrayList<>();
            status.add(1);
            status.add(3);
            status.add(4);
            testLambdaQueryWrapper.notIn(TestRequest::getStatus,status);
            Page<TestRequest> pageData = this.page(testRequestIPageParam, testLambdaQueryWrapper);
            return pageData;
        }

        return pageParam ;
    }
}
